package service

import (
	"errors"
	"gorm.io/gorm"
	"zsc-boot/app/customer/model"
	"zsc-boot/core/orm"
)

type OrderAddSvc struct {
}

func (o *OrderAddSvc) Create(req model.OrderAdd) error {
	//判断是否越界
	var orderModel model.Order
	if err := orm.GetDb().Where("id = ?", req.OrderId).Preload("OrderAdds").First(&orderModel).Error; err != nil {
		return err
	}

	var addMoney uint
	for _, v := range orderModel.OrderAdds {
		addMoney += v.Money
	}

	if addMoney+req.Money > orderModel.Money {
		return errors.New("金额超出")
	}
	return orm.GetDb().Transaction(func(tx *gorm.DB) error {
		if err := tx.Create(&req).Error; err != nil {
			return err
		}

		var isPayOff bool
		if addMoney+req.Money == orderModel.Money {
			isPayOff = true
		}
		if err := tx.Model(&model.Order{}).Where("id = ?", req.OrderId).
			Update("is_pay_off", isPayOff).Error; err != nil {
			return err
		}
		return nil
	})
}

func (o *OrderAddSvc) Update(req model.OrderAdd) (err error) {
	var orderAddModel model.OrderAdd
	if err = orm.GetDb().Where("id = ?", req.ID).Preload("OrderInfo.OrderAdds", func(db *gorm.DB) *gorm.DB {
		return db.Where("id != ?", req.ID)
	}).First(&orderAddModel).Error; err != nil {
		return err
	}

	var addMoney uint
	for _, v := range orderAddModel.OrderInfo.OrderAdds {
		addMoney += v.Money
	}

	if addMoney+req.Money > orderAddModel.OrderInfo.Money {
		return errors.New("金额超出")
	}

	return orm.GetDb().Transaction(func(tx *gorm.DB) error {
		if err = tx.Updates(&req).Error; err != nil {
			return err
		}

		var isPayOff bool
		if addMoney+req.Money == orderAddModel.OrderInfo.Money {
			isPayOff = true
		}
		if err = tx.Model(&model.Order{}).Where("id = ?", orderAddModel.OrderInfo.ID).
			Update("is_pay_off", isPayOff).Error; err != nil {
			return err
		}
		return nil
	})
}

func (o *OrderAddSvc) Delete(id uint) (err error) {
	var orderAddModel model.OrderAdd
	if err = orm.GetDb().Where("id = ?", id).Preload("OrderInfo").First(&orderAddModel).Error; err != nil {
		return err
	}
	err = orm.GetDb().Where("id = ?", id).Delete(&model.OrderAdd{}).Error

	var orderInfo model.Order
	if err = orm.GetDb().Where("id = ?", orderAddModel.OrderInfo.ID).Preload("OrderAdds").First(&orderInfo).Error; err != nil {
		return err
	}

	var addMoney uint
	for _, v := range orderInfo.OrderAdds {
		addMoney += v.Money
	}

	var isPayOff bool
	if addMoney == orderInfo.Money {
		isPayOff = true
	}
	if err = orm.GetDb().Model(&model.Order{}).Where("id = ?", orderAddModel.OrderInfo.ID).
		Update("is_pay_off", isPayOff).Error; err != nil {
		return err
	}

	return
}
